// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command
const villagerVotesCollection = db.collection('villagerVotes')
const userVotesCollection = db.collection('userVotes')

// 云函数入口函数
exports.main = async (event, context) => {
  console.log('vote 云函数被调用，参数:', event);
  
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  const { villagerId, villagerName, selectedAnimals } = event
  
  console.log('投票请求参数:', { openid, villagerId, villagerName, selectedAnimals })
  console.log('wxContext:', wxContext)
  
  // 支持批量投票
  const animalsToVote = selectedAnimals || (villagerId && villagerName ? [{ villagerId, villagerName }] : [])
  
  console.log('处理后的投票数据:', animalsToVote)
  console.log('参数验证详情:', { 
    openid: !!openid, 
    openidValue: openid,
    animalsToVoteLength: animalsToVote.length,
    selectedAnimals: selectedAnimals,
    villagerId: villagerId,
    villagerName: villagerName
  })
  
  if (!openid || animalsToVote.length === 0) {
    console.log('参数验证失败:', { openid: !!openid, animalsToVoteLength: animalsToVote.length })
    return {
      success: false,
      message: `参数不完整 - openid: ${!!openid}, animalsToVoteLength: ${animalsToVote.length}`,
      debug: {
        openid: !!openid,
        openidValue: openid,
        animalsToVoteLength: animalsToVote.length,
        selectedAnimals: selectedAnimals,
        event: event
      }
    }
  }

  try {
    // 检查数据库集合是否存在
    console.log('检查数据库集合...');
    
    // 设置今天的时间范围
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    const tomorrow = new Date(today)
    tomorrow.setDate(tomorrow.getDate() + 1)
    
    // 检查用户今天是否已经进行过任何投票活动（每人每天只能投票一次）
    const todayVotes = await userVotesCollection.where({
      openid,
      voteTime: _.gte(today).and(_.lt(tomorrow))
    }).get()
    
    if (todayVotes.data.length > 0) {
      return {
        success: false,
        message: '您今天已经投过票了，明天再来吧'
      }
    }

    // 记录用户投票（一次性记录所有选中的小动物）
    await userVotesCollection.add({
      data: {
        openid,
        voteTime: new Date(),
        voteType: 'batch',
        selectedAnimals: animalsToVote
      }
    })

    // 更新所有选中小动物的票数
    for (const animal of animalsToVote) {
      const villagerRecord = await villagerVotesCollection.where({
        villagerId: animal.villagerId
      }).get()

      if (villagerRecord.data.length === 0) {
        // 如果小动物没有投票记录，创建一个新记录
        await villagerVotesCollection.add({
          data: {
            villagerId: animal.villagerId,
            villagerName: animal.villagerName,
            votes: 1,
            updateTime: new Date()
          }
        })
      } else {
        // 如果小动物已有投票记录，更新票数
        await villagerVotesCollection.where({
          villagerId: animal.villagerId
        }).update({
          data: {
            votes: _.inc(1),
            updateTime: new Date()
          }
        })
      }
    }

    return {
      success: true,
      message: '投票成功'
    }
  } catch (error) {
    console.error('投票云函数错误:', error)
    console.error('错误详情:', {
      message: error.message,
      stack: error.stack,
      name: error.name
    })
    return {
      success: false,
      message: '投票失败，请稍后再试',
      error: error.message || error
    }
  }
}